import 'dart:ui';

import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get_it/get_it.dart';
import 'package:winkai/firebase_options.dart';
import 'package:winkai/helper/service_conf_helper.dart';
import 'package:winkai/helper/user_helper.dart';
import 'package:winkai/service/imp/msg_service_imp.dart';
import 'package:winkai/service/imp/ses_service_imp.dart';
import 'package:winkai/service/msg_service.dart';
import 'package:winkai/service/ses_service.dart';
import 'package:winkai/utils/package_info_utils.dart';

import 'my_app.dart';

bool _isRegisterService = false;
final getIt = GetIt.instance;

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  _registerService();

  ///设置只能竖屏
  await SystemChrome.setPreferredOrientations(
    [
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ],
  );
  await _initFb();
  await _initCommon();
  await _initAccount();
  runApp(const MyApp());
}

void _registerService() {
  if (!_isRegisterService) {
    getIt.registerLazySingleton<MsgService>(() => MsgServiceImp());
    getIt.registerLazySingleton<SesService>(() => SesServiceImp());
    _isRegisterService = true;
  }
}

Future<void> _initCommon() async {
  await PackageInfoUtils.init();
}

Future<void> _initFb() async {
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  const fatalError = true;
  // Async exceptions
  PlatformDispatcher.instance.onError = (error, stack) {
    if (fatalError) {
      // If you want to record a "fatal" exception
      FirebaseCrashlytics.instance.recordError(error, stack, fatal: true);
      // ignore: dead_code
    } else {
      // If you want to record a "non-fatal" exception
      FirebaseCrashlytics.instance.recordError(error, stack);
    }
    return true;
  };
  // Non-async exceptions
  FlutterError.onError = (errorDetails) {
    if (fatalError) {
      // If you want to record a "fatal" exception
      FirebaseCrashlytics.instance.recordFlutterFatalError(errorDetails);
      // ignore: dead_code
    } else {
      // If you want to record a "non-fatal" exception
      FirebaseCrashlytics.instance.recordFlutterError(errorDetails);
    }
  };
  await FirebaseCrashlytics.instance.setCrashlyticsCollectionEnabled(true);
  ServiceConfHelper().init();
}

Future<bool> _initAccount() async {
  return UserHelper().tryRegisterAccount(true);
}
